function f = cloth(array,Restlength,D,m,g)

% Converting array to 3d tensor
tensor = array2tensor(array);
N=length(tensor(:,1,1));

% Substracting the original tensor from a shifted one will yield the
% distances between the points in a particular dimension
hordistance=tensor(:,1:end-1,:)-tensor(:,2:end,:);
vertdistance=tensor(1:end-1,:,:)-tensor(2:end,:,:);
hordistance2=tensor(:,1:end-2,:)-tensor(:,3:end,:);
vertdistance2=tensor(1:end-2,:,:)-tensor(3:end,:,:);
diagdistance1=tensor(1:end-1,1:end-1,:)-tensor(2:end,2:end,:);
diagdistance2=tensor(1:end-1,2:end,:)-tensor(2:end,1:end-1,:);

% Calculating the norms of the distances
hornorm=sum(hordistance.^2,3).^.5;
vertnorm=sum(vertdistance.^2,3).^.5;
hornorm2=sum(hordistance2.^2,3).^.5;
vertnorm2=sum(vertdistance2.^2,3).^.5;
diagnorm1=sum(diagdistance1.^2,3).^.5;
diagnorm2=sum(diagdistance2.^2,3).^.5;

% Calculating the total potential energy in te springs
horenergy=((hornorm-Restlength).^2)*D;
vertenergy=((vertnorm-Restlength).^2)*D;
horenergy2=((hornorm2-2*Restlength).^2)*D;
vertenergy2=((vertnorm2-2*Restlength).^2)*D;
diagenergy=((diagnorm1-Restlength*sqrt(2)).^2)*D+ ...
    ((diagnorm2-Restlength*sqrt(2)).^2)*D;
% diagenergy=0;
% horenergy2 = 0;
% vertenergy2 = 0;

% Objective function is the sum of the energy in the springs and the
% gravitational energy;
f=sum(sum(horenergy))+sum(sum(vertenergy))+sum(sum(diagenergy))+...
    sum(sum(horenergy2))+sum(sum(vertenergy2))+...
    sum(sum(squeeze(m*g*tensor(:,:,3))));


end